package com.gxust.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.gxust.pojo.User;
import com.gxust.util.BaseContext;
import com.gxust.util.jwt.GetData;
import com.gxust.util.jwt.JwtUtils;
import com.gxust.util.result.Result;
import com.gxust.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户api
 */
@Slf4j
@RestController
//@CrossOrigin(origins = "*")
@Api(tags = "用户的api")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 用户信息
     */
    @Operation(summary ="用户信息上")
    @ApiImplicitParams({
            @ApiImplicitParam(name="UserID",value="用户Id",dataTypeClass = Long.class,
                    paramType = "query",example ="123"),
    })
    @GetMapping("/info")
    @ApiOperation("用户信息")
    public Result UserInfo(HttpServletRequest request){
        log.info("查询个人信息");
//        调用service函数
        Integer userId = GetData.getUserId(request);
        User userList = userService.list(userId);
        return  Result.success(userList);
    }


    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        //调用业务层：登录功能
        User loginEmp = userService.login(user);

        //判断：登录用户是否存在
        if(loginEmp !=null ){
            //自定义信息
            Map<String , Object> claims = new HashMap<>();
            claims.put("UserId", loginEmp.getUserId());
            claims.put("Username",loginEmp.getUsername());
            claims.put("FullName",loginEmp.getFullName());
            //使用JWT工具类，生成身份令牌
            String token = JwtUtils.generateJwt(claims);
            Map<String, Object> data = new HashMap<>();
            data.put("userRole", loginEmp.getUserRole());
            data.put("token", token);
            BaseContext.setUserId(loginEmp.getUserId());
            return Result.success(data);
        }
        return Result.error("用户名或密码错误");
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        //用户注册接口
        userService.add(user);
        return Result.success("注册成功");
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user,HttpServletRequest request) {
        log.info("修改个人信息");
        Integer userId = GetData.getUserId(request);
        user.setUserId(userId);
        userService.update(user);
        return Result.success("修改成功");
    }

}